package com.zhoug.map.amap;

import android.os.Bundle;
import android.util.Log;

import com.amap.api.maps.MapView;
import com.zhoug.map.core.ILifecycleListener;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

/**
 * 高德地图生命周期管理
 *
 * @Author 35574
 * @Date 2021/9/15
 * @Description
 */
public class AMapLifecycleHelper {
    private static final String TAG = ">>>AMapLifecycleHelper";
    private static boolean debug = false;

    private MapView mMapView;

    public AMapLifecycleHelper(@NonNull LifecycleOwner owner, @NonNull MapView mapView, Bundle savedInstanceState) {
        this.mMapView = mapView;
        mMapView.onCreate(savedInstanceState);
        owner.getLifecycle().addObserver(lifecycleListener);
    }

    /**
     * 存储数据
     * 需要在Activity或者Fragment的onSaveInstanceState方法中调用
     * @param outState
     */
    public void onSaveInstanceState(@NonNull Bundle outState) {
        if (mMapView != null) {
            mMapView.onSaveInstanceState(outState);
        }
    }

    /**
     * 销毁地图
     * 需要在Fragment的onDestroyView方法中调用
     */
    public void onDestroyView() {
        if (debug) {
            Log.d(TAG, "onDestroyView:");
        }
        if (mMapView != null) {
            mMapView.onDestroy();
            mMapView = null;
        }
    }

    private ILifecycleListener lifecycleListener = new ILifecycleListener() {
        @Override
        public void onCreate(@NonNull LifecycleOwner owner) {
            if (debug) {
                Log.d(TAG, "onCreate:");
            }
        }

        @Override
        public void onStart(@NonNull LifecycleOwner owner) {
            if (debug) {
                Log.d(TAG, "onStart:");
            }
        }

        @Override
        public void onResume(@NonNull LifecycleOwner owner) {
            if (debug) {
                Log.d(TAG, "onResume:");
            }
            if (mMapView != null) {
                mMapView.onResume();
            }
        }

        @Override
        public void onPause(@NonNull LifecycleOwner owner) {
            if (debug) {
                Log.d(TAG, "onPause:");
            }
            if (mMapView != null) {
                mMapView.onPause();
            }
        }

        @Override
        public void onStop(@NonNull LifecycleOwner owner) {
            if (debug) {
                Log.d(TAG, "onStop:");
            }
        }

        @Override
        public void onDestroy(@NonNull LifecycleOwner owner) {
            if (debug) {
                Log.d(TAG, "onDestroy:");
            }
            if (mMapView != null) {
                mMapView.onDestroy();
                mMapView = null;
            }
        }

        @Override
        public void onStateChange(@NonNull LifecycleOwner owner, Lifecycle.Event event) {

        }
    };

}
